package com.example.weather.ui.dashboard;

import static android.content.Intent.getIntent;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.weather.MyDataHelper;
import com.example.weather.cityModel;
import com.example.weather.databinding.FragmentDashboardBinding;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class DashboardFragment extends Fragment {

    private FragmentDashboardBinding binding;

    private final String baseUrl="https://api.vvhan.com/api/weather";
    private RequestQueue queue;
    private JsonObjectRequest jsonObjectRequest;
    DashboardViewModel dashboardViewModel;
    View root;

    String toCity=null;
    String toCollect=null;
    int toId=0;
    TextView cityName=null;
    TextView minTemperature=null;
    TextView maxTemperature=null;
    TextView type=null;
    TextView aqi=null;
    TextView aqiName=null;
    TextView winD=null;
    TextView winP=null;
    TextView day1=null;
    TextView day2=null;
    TextView day3=null;
    TextView day4=null;
    TextView day5=null;
    TextView day6=null;
    TextView day7=null;
    TextView day1_type=null;
    TextView day2_type=null;
    TextView day3_type=null;
    TextView day4_type=null;
    TextView day5_type=null;
    TextView day6_type=null;
    TextView day7_type=null;

    TextView day1_min=null;
    TextView day2_min=null;
    TextView day3_min=null;
    TextView day4_min=null;
    TextView day5_min=null;
    TextView day6_min=null;
    TextView day7_min=null;

    TextView day1_max=null;
    TextView day2_max=null;
    TextView day3_max=null;
    TextView day4_max=null;
    TextView day5_max=null;
    TextView day6_max=null;
    TextView day7_max=null;

    TextView day1_winD=null;
    TextView day2_winD=null;
    TextView day3_winD=null;
    TextView day4_winD=null;
    TextView day5_winD=null;
    TextView day6_winD=null;
    TextView day7_winD=null;

    TextView day1_winP=null;
    TextView day2_winP=null;
    TextView day3_winP=null;
    TextView day4_winP=null;
    TextView day5_winP=null;
    TextView day6_winP=null;
    TextView day7_winP=null;

    TextView queryCity=null;
    Button  query=null;
    Button button_c=null;

    MyDataHelper myDataHelper;
    Context context;

    @SuppressLint("SetTextI18n")
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        dashboardViewModel = new ViewModelProvider(this).get(DashboardViewModel.class);
        binding = FragmentDashboardBinding.inflate(inflater, container, false);
        root = binding.getRoot();
        //入口
        Log.d("switchPage", "当前页面我的天气");

        //初始化页面数据
        cityName=binding.cityName;
        minTemperature=binding.min;
        maxTemperature=binding.max;
        type=binding.type;
        aqi=binding.aqi;
        aqiName=binding.aqiName;
        winD=binding.windD;
        winP=binding.windP;
        day1=binding.day1;
        day2=binding.day2;
        day3=binding.day3;
        day4=binding.day4;
        day5=binding.day5;
        day6=binding.day6;
        day7=binding.day7;
        day1_type=binding.day1Type;
        day2_type=binding.day2Type;
        day3_type=binding.day3Type;
        day4_type=binding.day4Type;
        day5_type=binding.day5Type;
        day6_type=binding.day6Type;
        day7_type=binding.day7Type;
        day1_min=binding.day1Min;
        day2_min=binding.day2Min;
        day3_min=binding.day3Min;
        day4_min=binding.day4Min;
        day5_min=binding.day5Min;
        day6_min=binding.day6Min;
        day7_min=binding.day7Min;
        day1_max=binding.day1Max;
        day2_max=binding.day2Max;
        day3_max=binding.day3Max;
        day4_max=binding.day4Max;
        day5_max=binding.day5Max;
        day6_max=binding.day6Max;
        day7_max=binding.day7Max;
        day1_winD=binding.day1WindD;
        day2_winD=binding.day2WindD;
        day3_winD=binding.day3WindD;
        day4_winD=binding.day4WindD;
        day5_winD=binding.day5WindD;
        day6_winD=binding.day6WindD;
        day7_winD=binding.day7WindD;
        day1_winP=binding.day1WindP;
        day2_winP=binding.day2WindP;
        day3_winP=binding.day3WindP;
        day4_winP=binding.day4WindP;
        day5_winP=binding.day5WindP;
        day6_winP=binding.day6WindP;
        day7_winP=binding.day7WindP;
        queryCity=binding.editText;
        query=binding.query;
        button_c=binding.button;
        context = getContext();
        //初始化数据库
        myDataHelper=new MyDataHelper(context);
        // 初始化RequestQueue
        queue = Volley.newRequestQueue(requireContext());


        // 获取传递过来的数据
        Bundle bundle = getArguments();
        if (bundle != null) {
            //在收藏跳转过来的
            toCity = bundle.getString("name");
            toCollect=bundle.getString("collect");
            toId=bundle.getInt("id");
            cityName.setText(toCity+"天气加载中");
            Toast.makeText(context,"正在加载"+toCity,Toast.LENGTH_SHORT).show();
            getWeather(baseUrl+"?city="+toCity);
        }else{
            //根据网络IP获取所处城市天气信息
            cityName.setText("珠海市");
            toCollect="no";
            Toast.makeText(context,"正在加载珠海市",Toast.LENGTH_SHORT).show();
            getWeather(baseUrl+"?city="+"珠海市");
        }

        //点击查询按钮
        query.setOnClickListener((v -> {
            Log.d("click","查询天气");
            Toast.makeText(context,"正在加载"+queryCity.getText().toString().trim(),Toast.LENGTH_SHORT).show();
            getWeather(baseUrl+"?city="+queryCity.getText().toString().trim());
            cityName.setText(queryCity.getText().toString()+"天气加载中");
            toCollect="off";
            queryCity.setText("");
        }));


        //点击收藏按钮
        button_c.setOnClickListener((v -> {
            if(toCollect=="off"||toCollect==null){
                cityModel citymodel=new cityModel(-1,cityName.getText().toString(),"no");
                myDataHelper=new MyDataHelper(context);
                String s=myDataHelper.addOne(citymodel);
            }
        }));
        return root;
    }

    //获取天气数据
    private void getWeather(String url){
        //创建一个JsonObjectRequest对象
        jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject res) {
                Log.d("Weather Response", res.toString());

                //更新界面
                JSONObject data= null;
                JSONObject air= null;
                try {
                    air = res.getJSONObject("air");
                    data = res.getJSONObject("data");
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                try {
                    cityName.setText(res.getString("city"));

                    maxTemperature.setText(data.getString("high"));
                    minTemperature.setText(data.getString("low"));
                    type.setText(data.getString("type"));
                    winD.setText(data.getString("fengxiang"));
                    winP.setText(data.getString("fengli"));

                    aqi.setText(air.getString("aqi"));
                    aqiName.setText(air.getString("aqi_name"));

                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                //获取未来7天数据
                try {
                    get7DayWeather(baseUrl+"?city="+res.getString("city")+"&type=week");
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError err) {
                cityName.setText("加载失败");
                Log.d("Weather Error", err.toString());
            }

        });
        queue.add(jsonObjectRequest);
    }

    //获取一周天气数据
    private void get7DayWeather(String url){
        //创建一个JsonObjectRequest对象
        jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject res) {
                Log.d("7DayWeather Response", res.toString());
                Toast.makeText(context,"加载成功",Toast.LENGTH_SHORT).show();
                //更新界面
                JSONArray data= null;
                JSONObject Day1=null;
                JSONObject Day2=null;
                JSONObject Day3=null;
                JSONObject Day4=null;
                JSONObject Day5=null;
                JSONObject Day6=null;
                JSONObject Day7=null;
                try {
                    data = res.getJSONArray("data");
                    Day1 = data.getJSONObject(0);
                    Day2 = data.getJSONObject(1);
                    Day3 = data.getJSONObject(2);
                    Day4 = data.getJSONObject(3);
                    Day5 = data.getJSONObject(4);
                    Day6 = data.getJSONObject(5);
                    Day7 = data.getJSONObject(6);

                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }

                try {
                    day1.setText(Day1.getString("week"));
                    day2.setText(Day2.getString("week"));
                    day3.setText(Day3.getString("week"));
                    day4.setText(Day4.getString("week"));
                    day5.setText(Day5.getString("week"));
                    day6.setText(Day6.getString("week"));
                    day7.setText(Day7.getString("week"));
                    day1_type.setText(Day1.getString("type"));
                    day2_type.setText(Day2.getString("type"));
                    day3_type.setText(Day3.getString("type"));
                    day4_type.setText(Day4.getString("type"));
                    day5_type.setText(Day5.getString("type"));
                    day6_type.setText(Day6.getString("type"));
                    day7_type.setText(Day7.getString("type"));

                    day1_min.setText(Day1.getString("low"));
                    day2_min.setText(Day2.getString("low"));
                    day3_min.setText(Day3.getString("low"));
                    day4_min.setText(Day4.getString("low"));
                    day5_min.setText(Day5.getString("low"));
                    day6_min.setText(Day6.getString("low"));
                    day7_min.setText(Day7.getString("low"));

                    day1_max.setText(Day1.getString("high"));
                    day2_max.setText(Day2.getString("high"));
                    day3_max.setText(Day3.getString("high"));
                    day4_max.setText(Day4.getString("high"));
                    day5_max.setText(Day5.getString("high"));
                    day6_max.setText(Day6.getString("high"));
                    day7_max.setText(Day7.getString("high"));

                    day1_winD.setText(Day1.getString("fengxiang"));
                    day2_winD.setText(Day2.getString("fengxiang"));
                    day3_winD.setText(Day3.getString("fengxiang"));
                    day4_winD.setText(Day4.getString("fengxiang"));
                    day5_winD.setText(Day5.getString("fengxiang"));
                    day6_winD.setText(Day6.getString("fengxiang"));
                    day7_winD.setText(Day7.getString("fengxiang"));

                    day1_winP.setText(Day1.getString("fengli"));
                    day2_winP.setText(Day2.getString("fengli"));
                    day3_winP.setText(Day3.getString("fengli"));
                    day4_winP.setText(Day4.getString("fengli"));
                    day5_winP.setText(Day5.getString("fengli"));
                    day6_winP.setText(Day6.getString("fengli"));
                    day7_winP.setText(Day7.getString("fengli"));

                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError err) {
                Log.d("7DayWeather Error", err.toString());
            }
        });
        queue.add(jsonObjectRequest);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (queue != null && jsonObjectRequest != null) {
            queue.cancelAll(jsonObjectRequest);
        }
        queue = null;
        jsonObjectRequest = null;
        binding = null;
    }
}